<route lang="json5" type="page">
{
  style: {
    navigationBarTitleText: '登录',
    navigationStyle: 'custom',
  },
}
</route>

<template>
  <view
    class="login-container"
    :style="{
      fontSize: settingsStore.fontSize,
      backgroundColor: settingsStore.themeLightColor,
      color: settingsStore.themeColor,
    }"
  >
    <!-- 背景装饰元素 -->
    <view class="bg-decoration bg-circle-1"></view>
    <view class="bg-decoration bg-circle-2"></view>
    <view class="bg-decoration bg-circle-3"></view>

    <view class="login-header" :style="{ color: settingsStore.themeColor }">
      <image class="login-logo" :src="appLogo" mode="aspectFit"></image>
      <view class="login-title">{{ appTitle }}</view>
    </view>

    <view class="login-form">
      <view
        class="welcome-text"
        :style="{ fontSize: settingsStore.titleSize, color: settingsStore.themeColor }"
      >
        欢迎登录
      </view>
      <view class="login-desc" :style="{ fontSize: settingsStore.fontSize, color: '#666' }">
        请使用手机号一键登录
      </view>

      <!-- 登录按钮组 -->
      <view class="login-buttons">
        <!-- 微信小程序一键登录按钮 -->
        <!-- #ifdef MP-WEIXIN -->
        <button
          v-if="!localIsLogin"
          type="primary"
          open-type="getPhoneNumber"
          @getphonenumber="handleGetPhoneNumber"
          class="wechat-login-btn"
          :style="{
            backgroundColor: settingsStore.themeColor,
            fontSize: settingsStore.fontSize,
            color: '#fff',
          }"
        >
          手机号一键登录
        </button>
        <!-- #endif -->
        <button
          v-else
          @click="loginBtn"
          class="wechat-login-btn"
          :style="{
            backgroundColor: settingsStore.themeColor,
            fontSize: settingsStore.fontSize,
            color: '#fff',
          }"
        >
          手机号一键登录
        </button>

        <!-- 返回上一页按钮 -->
        <button
          @click="handleBack"
          class="back-btn"
          :style="{
            fontSize: settingsStore.fontSize,
            borderColor: settingsStore.themeColor,
            color: settingsStore.themeColor,
          }"
        >
          返回
        </button>
      </view>
    </view>

    <view class="login-footer"></view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useUserStore } from '@/store/user'
import { useSettingsStore } from '@/store/settings'
import { isTableBar } from '@/utils/index'
import { useToast } from 'wot-design-uni'

const toast = useToast()

const redirectRoute = ref('')

const localIsLogin = uni.getStorageSync('phone') ? true : false

const appTitle = ref(import.meta.env.VITE_APP_TITLE || 'Login')
const appLogo = ref(import.meta.env.VITE_APP_LOGO || '/static/logo.png')

const encryptedData = ref('')
const iv = ref('')
const wxCode = ref('')

const userStore = useUserStore()
const settingsStore = useSettingsStore()

const agreePrivacy = ref(true) // 默认已同意

onLoad((option) => {
  if (option.redirect) {
    redirectRoute.value = option.redirect
  }
})

const handleGetPhoneNumber = async (e: any) => {
  if (e.detail.errMsg === 'getPhoneNumber:fail user deny') {
    toast.info('您已拒绝授权手机号')
    return
  }

  if (!agreePrivacy.value) {
    toast.info('请先阅读并同意用户协议和隐私政策')
    return
  }
  wxCode.value = e.detail.code
  encryptedData.value = e.detail.encryptedData
  iv.value = e.detail.iv

  try {
    uni.showLoading({
      title: '登录中...',
      forbidClick: true,
      loadingType: 'spinner',
    })
    // 调用登录接口，传入 code, encryptedData 和 iv
    await userStore.wxLogin({
      encryptedData: encryptedData.value,
      iv: iv.value,
      wxCode: wxCode.value,
    })
    uni.hideLoading()
    toast.success('登录成功')

    setTimeout(() => {
      const targetUrl = redirectRoute.value || '/pages/index/index'
      if (isTableBar(targetUrl)) {
        uni.switchTab({ url: targetUrl })
      } else {
        uni.redirectTo({ url: targetUrl })
      }
    }, 1000)
  } catch (error) {
    console.log('登录失败:', error)
    toast.error('登录失败，请重试')
  }
}

const loginBtn = async () => {
  console.log('普通登录')
  try {
    uni.showLoading({
      title: '登录中...',
      forbidClick: true,
      loadingType: 'spinner',
    })
    await userStore.Login({
      phone: uni.getStorageSync('phone'),
    })
    uni.hideLoading()
    toast.success('登录成功')

    setTimeout(() => {
      const targetUrl = redirectRoute.value || '/pages/index/index'
      if (isTableBar(targetUrl)) {
        uni.switchTab({ url: targetUrl })
      } else {
        uni.redirectTo({ url: targetUrl })
      }
    }, 1000)
  } catch (error) {
    console.log('登录失败:', error)
    toast.error('登录失败，请重试')
  }
}

const handleBack = () => {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
.login-container {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  padding: 0 70rpx;
  /* 背景色由主题动态控制 */
  /* background-color: #ffffff; */
  background-image: linear-gradient(
    135deg,
    rgba(25, 137, 250, 0.05) 0%,
    rgba(255, 255, 255, 0) 100%
  );
  position: relative;
  overflow: hidden;
}

/* 背景装饰元素 */
.bg-decoration {
  position: absolute;
  border-radius: 50%;
  background: linear-gradient(135deg, rgba(25, 137, 250, 0.05), rgba(25, 137, 250, 0.1));
  z-index: 0;
  pointer-events: none;
}

.bg-circle-1 {
  width: 500rpx;
  height: 500rpx;
  top: -200rpx;
  right: -200rpx;
  opacity: 0.6;
}

.bg-circle-2 {
  width: 400rpx;
  height: 400rpx;
  bottom: 10%;
  left: -200rpx;
  opacity: 0.4;
}

.bg-circle-3 {
  width: 300rpx;
  height: 300rpx;
  bottom: -100rpx;
  right: 10%;
  opacity: 0.3;
  background: linear-gradient(135deg, rgba(7, 193, 96, 0.05), rgba(7, 193, 96, 0.1));
}

.login-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-top: 200px;
  animation: fadeInDown 0.8s ease-out;

  .login-logo {
    width: 200rpx;
    height: 200rpx;
    border-radius: 36rpx;
    box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.12);
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.95);
      box-shadow: 0 6rpx 15rpx rgba(0, 0, 0, 0.1);
    }
  }

  .login-title {
    margin-top: 30rpx;
    font-size: 46rpx;
    font-weight: bold;
    /* 颜色由主题动态控制 */
    /* color: #333333; */
    letter-spacing: 3rpx;
    text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.05);
  }
}

.login-form {
  flex: 1;
  margin-top: 70rpx;
  animation: fadeIn 0.8s ease-out 0.2s both;

  .welcome-text {
    margin-bottom: 16rpx;
    /* 字体大小由主题动态控制 */
    /* font-size: 48rpx; */
    font-weight: bold;
    /* 颜色由主题动态控制 */
    /* color: #333333; */
    text-align: center;
    letter-spacing: 1rpx;
  }

  .login-desc {
    margin-bottom: 70rpx;
    /* 字体大小由主题动态控制 */
    /* font-size: 28rpx; */
    color: #888888;
    text-align: center;
  }

  .login-buttons {
    display: flex;
    flex-direction: column;
    gap: 36rpx;

    button {
      height: 66rpx;
      line-height: 66rpx;
      /* 字体大小由主题动态控制 */
      /* font-size: 28rpx; */
      border-radius: 33rpx;
      transition: all 0.3s ease;
      margin: 0;
      padding: 0;
      display: flex;
      align-items: center;
      justify-content: center;

      &:active {
        transform: scale(0.98);
      }
    }

    .wechat-login-btn {
      /* 背景色由主题动态控制 */
      /* background-color: #07c160; */
      color: #fff;
      border: none;

      &[disabled] {
        background-color: #9ed5a7;
        opacity: 0.7;
      }
    }

    .back-btn {
      background-color: transparent;
      /* 边框和文字颜色由主题动态控制 */
      /* color: #999; */
      border: 1px solid #ccc;

      &:active {
        background-color: rgba(0, 0, 0, 0.05);
      }
    }
  }
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
